package com.jike.noobmoney.mvp.view.activity;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.jike.noobmoney.R;
import com.jike.noobmoney.adapter.TaskCategoryAdapter;
import com.jike.noobmoney.adapter.TaskListAdapter;
import com.jike.noobmoney.contants.ConstantValue;
import com.jike.noobmoney.entity.BaseEntity;
import com.jike.noobmoney.entity.CateListEntity;
import com.jike.noobmoney.entity.MyTaskEntity;
import com.jike.noobmoney.entity.TaskListEntity;
import com.jike.noobmoney.entity.UserInfoEntity;
import com.jike.noobmoney.mvp.presenter.TaskPresenter;
import com.jike.noobmoney.mvp.view.widget.CheckableTextView;
import com.jike.noobmoney.mvp.view.widget.MyGridView;
import com.jike.noobmoney.net.IView;
import com.jike.noobmoney.net.RetrofitHelper;
import com.jike.noobmoney.util.AppInfoUtils;
import com.jike.noobmoney.util.RecordSQLiteOpenHelper;
import com.jike.noobmoney.util.SPUtils;
import com.jike.noobmoney.util.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class TastListActivity extends BaseActivity implements IView {


    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.tv_all_show)
    TextView tv_all_show;

    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.rv_list)
    MyGridView rv_list;
    @BindView(R.id.ctv_show)
    CheckableTextView checkableTextViewTime;
    @BindView(R.id.ck_rq)
    CheckableTextView checkableTextViewRQ;
    @BindView(R.id.ck_price)
    CheckableTextView checkableTextViewPRICE;
    private TaskCategoryAdapter taskCategoryAdapter;
    private TaskListAdapter adapter;

    private ArrayList<CateListEntity.CatelistBean> list=new ArrayList<CateListEntity.CatelistBean>();
    private List<TaskListEntity.TaskBean> mData = new ArrayList<>();
    private boolean isRefresh = true;
    private TaskPresenter taskPresenter;
    private String userid = "";
    private View headerView;
    private ImageView iv_back;
    private int page = 1;
    private String c_id = "0";
    private int sortclasses=1;
    private int sorttype=1;

    public boolean flag=true;

    @Override
    protected int layoutResID() {
        return R.layout.activity_task_list;
    }
    @Override
    public boolean ismain() {
        return true;
    }
    @Override
    public Boolean isfits() {
        return true;
    }
    @Override
    protected void initData() {
        taskPresenter = new TaskPresenter(this);
        userid = SPUtils.getInstance().getString(ConstantValue.SpType.userid);
        taskPresenter.getCatelist(ConstantValue.RequestKey.task_type);
        initView();
        getData(true);
        refreshType(true);

    }

    @OnClick({R.id.iv_back,R.id.ctv_show,R.id.ck_rq,R.id.ck_price,R.id.tv_all_show})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_all_show:
                refreshType(true);
                taskCategoryAdapter.setSelectedPosition(-1);
                taskCategoryAdapter.notifyDataSetChanged();
                c_id = "0";
                sortclasses=1;
                sorttype=1;
                getData(true);
                break;
            case R.id.ctv_show:
                if(checkableTextViewTime.isChecked()){
                    sorttype=1;
                    checkableTextViewTime.setChecked(false);
                }else
                {
                    sorttype=2;
                    checkableTextViewTime.setChecked(true);
                }
                checkableTextViewRQ.setChecked(false);
                checkableTextViewPRICE.setChecked(false);
                sortclasses=2;
                getData(true);
                break;
            case R.id.ck_rq:
                if(checkableTextViewRQ.isChecked()){
                    sorttype=1;
                    checkableTextViewRQ.setChecked(false);
                }else
                {
                    sorttype=2;
                    checkableTextViewRQ.setChecked(true);
                }
                checkableTextViewTime.setChecked(false);
                checkableTextViewPRICE.setChecked(false);
                sortclasses=3;
                getData(true);
                break;
            case R.id.ck_price:
                if(checkableTextViewPRICE.isChecked()){
                    sorttype=1;
                    checkableTextViewPRICE.setChecked(false);
                }else
                {
                    sorttype=2;
                    checkableTextViewPRICE.setChecked(true);
                }
                checkableTextViewRQ.setChecked(false);
                checkableTextViewTime.setChecked(false);
                sortclasses=4;
                getData(true);
                break;
        }
    }

    private void refreshType(boolean isSelected) {
        if (isSelected) {
            //默认选中
            flag=true;
            tv_all_show.setTextColor(getResources().getColor(R.color.red));
        } else {
            //选择链接
            flag=false;
            tv_all_show.setTextColor(getResources().getColor(R.color.hint_color));
        }
    }

        /**
         * 获取数据
         */
    private void getData(boolean isRefresh) {
        this.isRefresh = isRefresh;
        if (isRefresh) {
            page = 1;
        } else {
            page++;
        }
        showProgress();
        userid = SPUtils.getInstance().getString(ConstantValue.SpType.userid);
        taskPresenter.getTasklist(userid,c_id, "" + page, "100",sortclasses+"",sorttype+"", ConstantValue.RequestKey.task_list);
    }

    @Override
    public void onSuccess(String code, String msg, Object data, String actionType) {
        disLoading();
        if (ConstantValue.RequestKey.task_type.equals(actionType)) {
            List<CateListEntity.CatelistBean> catelist = (List<CateListEntity.CatelistBean>) data;

            if (catelist != null && catelist.size() > 0) {
                list.clear();
                list.addAll(catelist);
                taskCategoryAdapter.notifyDataSetChanged();
            }

        }
        if (ConstantValue.RequestKey.task_list.equals(actionType)) {
            List<TaskListEntity.TaskBean> task = (List<TaskListEntity.TaskBean>) data;
            if (task != null && task.size() > 0) {
                if (isRefresh) {
                    mData.clear();
                    mData.addAll(task);
                } else {
                    mData.addAll(task);
                }

            }
          //  getIdata(i);
            adapter.refresh(mData);
        }
        if (ConstantValue.RequestKey.my_task.equals(actionType)) {
            List<MyTaskEntity.OrderlistBean> orderlist = (List<MyTaskEntity.OrderlistBean>) data;
            if (orderlist != null && orderlist.size() > 0) {
                //需要保存手机号：
                //第三步
                    insertData(orderlist.get(0).mobile);

                setCancleOrder(orderlist.get(0).getO_id()+"");


            } else {

            }
        }
    }

    public void getIdata(int i)
    {

        if(i<=mData.size()-1) {
            getTaskOrder(mData.get(i).getT_id() + "");
        }
    }
    public int i;
    /**
     * 取消任务
     */
    public Call<BaseEntity> cancleOrder;
    public void setCancleOrder(String  orderId) {

        cancleOrder = RetrofitHelper.getInstance().cancleOrder(userid, orderId);
        cancleOrder.enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                if (response != null) {
                    BaseEntity body = response.body();
                    if (body != null) {
                        if ("100".equals(body.getCode())) {
                          i++;
                            getIdata(i);
                        } else {
                            ToastUtils.showShortToastSafe(body.getRinfo());
                        }
                    }
                    dismissProgress();

                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                ToastUtils.showShortToastSafe(t.getMessage());
                dismissProgress();
            }
        });


    }


    /**
     * 领取任务
     */
    private RecordSQLiteOpenHelper helper = new RecordSQLiteOpenHelper(this);;
    private SQLiteDatabase db;
    private Call<BaseEntity> taskOrder;
    public void getTaskOrder(String taskId) {
        taskOrder = RetrofitHelper.getInstance().getTaskOrder(userid, taskId);
        taskOrder.enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                if (response != null) {
                    BaseEntity body = response.body();
                    if (body != null) {
                        if ("100".equals(body.getCode())) {
                            //领取成功  跳转到我的任务页面
                          //  startActivity(new Intent(TaskDetailActivity.this, MyTaskActivity.class));
                          //  finish();
                            //第二步
                            getData();
                        } else {
                            i++;
                            getIdata(i);
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                ToastUtils.showLongToast(t.getMessage());
            }
        });
    }

    /**
     * 拉取订单
     */
    private void getData() {
        if (taskPresenter != null) {
            taskPresenter.getMyTask(userid, "1", ConstantValue.RequestKey.my_task);
        }

    }



    private Call<UserInfoEntity> userInfoCall;
    /**
     * 获取个人信息
     */
    private void getData(String uid) {
        userInfoCall = RetrofitHelper.getInstance().getUserInfo(uid);
        userInfoCall.enqueue(new Callback<UserInfoEntity>() {
            @Override
            public void onResponse(Call<UserInfoEntity> call, Response<UserInfoEntity> response) {
                if (response != null) {
                    UserInfoEntity body = response.body();
                    if (body != null && "100".equals(body.getCode())) {
                        UserInfoEntity.UserBean user = body.getUser();
                        if (user != null) {

                            Log.d("mobile",user.getMobile());
                            FileUtils.writeTxtToFile(user.getMobile(),"/sdcard/phone/","phone.txt");
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<UserInfoEntity> call, Throwable t) {
                ToastUtils.showShortToastSafe(t.getMessage());
            }
        });
    }


    @Override
    public void onFailed(String code, String msg) {
        disLoading();
    }

    private void initView() {
        tv_title.setText("悬赏大厅");
//        headerView = LayoutInflater.from(context).inflate(R.layout.activity_task_list_head, null, false);
//
//        tv_title=(TextView)headerView.findViewById(R.id.tv_title);
//        tv_title.setText("悬赏大厅");
//        iv_back=(ImageView) headerView.findViewById(R.id.iv_back);
//        iv_back.setOnClickListener(this);
//        rv_list=(MyGridView)headerView.findViewById(R.id.rv_list);
//        taskCategoryAdapter=new TaskCategoryAdapter(context,list);
//        rv_list.setAdapter(taskCategoryAdapter);
//        rv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                taskCategoryAdapter.setSelectedPosition(i);
//                taskCategoryAdapter.notifyDataSetChanged();
//            }
//        });
//
//        checkableTextViewTime=(CheckableTextView)headerView.findViewById(R.id.ctv_show);
//        checkableTextViewTime.setOnClickListener(this);
//
//        checkableTextViewRQ=(CheckableTextView) headerView.findViewById(R.id.ck_rq);
//        checkableTextViewRQ.setOnClickListener(this);
//
//        checkableTextViewPRICE=(CheckableTextView)headerView.findViewById(R.id.ck_price);
//        checkableTextViewPRICE.setOnClickListener(this);

        taskCategoryAdapter=new TaskCategoryAdapter(context,list);
        rv_list.setAdapter(taskCategoryAdapter);
        rv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                CateListEntity.CatelistBean bean =(CateListEntity.CatelistBean)adapterView.getAdapter().getItem(i);
                taskCategoryAdapter.setSelectedPosition(i);
                taskCategoryAdapter.notifyDataSetChanged();
                c_id=bean.getC_id()+"";
                checkableTextViewRQ.setChecked(false);
                checkableTextViewPRICE.setChecked(false);
                checkableTextViewTime.setChecked(false);
                flag=false;
                refreshType(flag);
                sortclasses=1;
                mData.clear();
                getData(true);
            }
        });

        adapter = new TaskListAdapter(context);
        recyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(adapter);
        //item点击
        adapter.setOnItemClickListener((adapterView, view, position, l) -> {
            TaskListEntity.TaskBean item = (TaskListEntity.TaskBean) adapter.getItem(position);
            Intent intent = new Intent(context, TaskDetailActivity.class);
            intent.putExtra(TaskDetailActivity.t_id, "" + item.getT_id());
            startActivity(intent);
        });

        refreshLayout.setOnRefreshListener(refreshlayout -> {
            getData(true);
        });

        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            getData(false);
        });
    }


    private void disLoading() {
        dismissProgress();
        if (refreshLayout != null) {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
        }
    }
    /**
     * 插入数据
     */
    private void insertData(String tempName) {
        db = helper.getWritableDatabase();
        db.execSQL("insert into records(name) values('" + tempName + "')");
        db.close();
    }

}
